<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品咨询类
 * @package  module
 * @author   allen.qiang
 * @version 1.0
 */

class goodsConsult {

    private $dbca;//数据库实例

    function __construct(&$dbca) {
        $this->dbca = $dbca;
    }

    /**
     * 查询商品咨询信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'pcustID' => int 客户号
     *       'consultStatus' => int 0:未回复 1:已回复
     *       'recommendFlg' => int 首页推荐标志 0:不推荐 1:推荐
     *       'displayFlg' => int 显示标志 0:针对此用户显示 1:对所有用户显示
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchConsult( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //二级网购号
        if (isset($arg_array['twoPostID']) && is_numeric($arg_array['twoPostID'])) {
            $sql .= ' AND cc.twoPostID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['twoPostID'];
        }

        //回复状态
        if (isset($arg_array['consultStatus']) && is_numeric($arg_array['consultStatus'])) {
            $sql .= ' AND cc.consultStatus = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['consultStatus'];
        }

        //客户号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND cc.pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //首页推荐标志 0:不推荐 1:推荐
        if (isset($arg_array['recommendFlg']) && in_array($arg_array['recommendFlg'], array(0 ,1))) {
            $sql .= ' AND cc.recommendFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['recommendFlg'];
        }

        //显示标志 0:针对此用户显示 1:对所有用户显示
        if (isset($arg_array['displayFlg']) && in_array($arg_array['displayFlg'], array(0, 1))) {
            $sql .= ' AND cc.displayFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['displayFlg'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM content_consult cc ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT cc.*,cm.custID,cm.head_pic,cm.rankName FROM content_consult cc
                           INNER JOIN cust_master cm ON cm.pcustID = cc.pcustID ' . $sql;
            error_log($search_sql);
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'custID' => $item->custID,
                    'head_pic' => set_cust_head_pic( $item->head_pic ),
                    'rankName' => $item->rankName,
                    'goodsName' => $item->goodsName,
                    'link' => set_goods_link( $item->postID ),
                    'img_link' => set_goods_img_link( $item->goodsMainPic ),
                    'createTime' => $item->createTime,
                    'info' => $item->consultInfo,
                    'ip' => $item->ipAddress,
                    'status' => $item->commentStatus,
                    'answerInfo' => $item->answerInfo,
                    'answerUserID' => $item->answerUserID,
                    'answerDateTime' => $item->answerDateTime,
                    'satisfaction' => $item->satisfaction,
                    'creator' => $item->creator,
                    'consultStatus' => $item->consultStatus
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 咨询回复
     * @param array $arg_array 参数数组
     * @return array
     * @throws Exception
     */
    public function changeConsultReplySatisfied( $arg_array ) {

        if (!isset($arg_array['uuid'], $arg_array['satisfaction']) || empty($arg_array['uuid']) || !in_array($arg_array['satisfaction'], array(1, 2)))
            return array('code' => 400, 'message' => '参数错误');

        try {

            $consult_obj = new entity('content_consult');
            $consult_obj->uuid = $arg_array['uuid'];
            if (!$this->dbca->fetch($consult_obj))
                throw new Exception("咨询信息没有找到", 404);
            if ($consult_obj->satisfaction == 1 || $consult_obj->satisfaction == 2)
                throw new Exception("咨询已评价", 406);
            $consult_obj->satisfaction = $arg_array['satisfaction'];
            if (!$this->dbca->save($consult_obj))
                throw new Exception("页面已失效，请刷新页面重试", 404);

            return array( 'code' => 200, 'message' => 'ok' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }


    }

    /**
     * 删除商品咨询
     * @author raohenglei
     */
    public function deleteGoodsConsult ( &$arg_array ) {

        if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '请选择要删除的商品咨询' );

        $delete_array = explode('_', $arg_array['delete_str']);

        try {

            foreach($delete_array as &$consult_uuid) {

                if (strlen($consult_uuid) != 32)
                    return array( 'code' => 400, 'message' => '参数错误' );

                //查询资源位信息
                $consult_obj = new entity('content_consult');
                $consult_obj->uuid = $consult_uuid;
                if ($this->dbca->fetch($consult_obj)) {
                    $this->dbca->delete($consult_obj);
                }

            }

            return array( 'code' => 200, 'message' => '删除成功' );

        } catch (Exception $e) {

            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );

        }
    }


    /**
     * 商品咨询处理
     * @author raohenglei
     * @param array $arg_array 参数数组
     * @return array
     */
    public function dealGoodsConsult ( $arg_array ) {

        $uuid = $arg_array['uuid'];

        try{

            $getConsultInfo 				= new entity('content_consult');
            $getConsultInfo->uuid 			= $uuid;

            if (!$this->dbca->fetch($getConsultInfo)) {
                throw new Exception('商品咨询信息没有找到，请与管理员联系', 404);
            }
            $getConsultInfo->answerInfo		= $arg_array['content'].sprintf('感谢您对%s的支持！祝您购物愉快！',G_MAIL_SENDER_NAME);
            $getConsultInfo->consultStatus 	= 1;
            $getConsultInfo->answerUserID 	= $arg_array['answerUserID'];
            $getConsultInfo->answerDateTime = $arg_array['answerDateTime'];
            $getConsultInfo->displayFlg 	= $arg_array['displayFlg'];
            $getConsultInfo->recommendFlg 	= $arg_array['recommendFlg'];
            $this->dbca->save($getConsultInfo,'content');

            return array( 'code' => 200, 'message' => '商品咨询已处理' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                return array( 'code' => 500, 'message' => '系统异常，请与管理员联系' );
            }

        }
    }

    /**
     * 保存商品咨询信息
     * @param $arg_array
     * $arg_array = array(
     *      'info' => string 咨询内容
     *      'postID' => int 三级商品网购号
     *      'pcustID' => int 客户号
     *      'ip' => string ip地址
     * )
     * @return array
     */
    public function addGoodsConsult( $arg_array ) {

        //检查参数
        if (!isset($arg_array['info'], $arg_array['postID'], $arg_array['pcustID'], $arg_array['ip']) || !is_numeric($arg_array['twoPostID']) || !is_numeric($arg_array['pcustID']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['info']))
            return array( 'code' => 400, 'message' => '咨询内容不能为空' );

        //实例公共类
        $commHandler = new commHandler( $this->dbca );

        try {

            //网购号
            $postID = $arg_array['postID'];
            $info   = $arg_array['info'];
            $ip     = $arg_array['ip'];

            //检查会员信息
            $arg_array = array( 'pcustID' => $arg_array['pcustID'] );
            $cust_array = $commHandler->search($arg_array, 'cust_master');
            if (!$cust_array)
                return array( 'code' => 404, 'message' => '会员信息没有找到' );
            $cust_obj = &$cust_array[0];

            //查询商品信息
            $arg_array = array( 'postID' => $postID );
            $goods_array = $commHandler->search($arg_array, 'goods_sale');

            if (!$goods_array)
                return array( 'code' => 404, 'message' => '商品信息没有找到' );
            $goods_obj = &$goods_array[0];

            //保存咨询信息
            $consult_obj = new entity('content_consult');
            $consult_obj->creator = $cust_obj->custID;
            $consult_obj->pcustID = $cust_obj->pcustID;
            $consult_obj->consultInfo = $commHandler->convertVar($info);
            $consult_obj->postID = $postID;
            $consult_obj->twoPostID = $goods_obj->twoPostID;
            $consult_obj->goodsName = $goods_obj->goodsName;
            $consult_obj->goodsMainPic = $goods_obj->goodsMainPic;
            $consult_obj->ipAddress = $ip;
            $consult_obj->consultStatus = 0;
            $this->dbca->save($consult_obj);

            return array( 'code' => 200, 'message' => '商品咨询保存成功' );

        } catch (Exception $e) {

            return array( 'code' => 500, 'message' => '系统错误' );

        }

    }

}